package com.study.design.model.createPattern.prototype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Date;

import org.junit.Test;

/**
* @Name: Client
* @Description: 原型模式测试客户端
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-10 下午7:18:16 
* @Version: V1.0
 */
public class Client {
	
	/**
	* @Name: lightCopy
	* @Description: 浅克隆测试类
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-10 下午7:24:06
	* @Parameters: @throws Exception
	* @Return: void
	 */
	@Test
	public void lightCopy() throws Exception {
		Date date = new Date(12323122312L) ;
		LightCopySheep sh01 = new LightCopySheep("单利", date) ;
		System.out.println(sh01.getName());
		System.out.println(sh01.getBirthday());
		LightCopySheep sh02 = (LightCopySheep) sh01.clone() ; //浅克隆
		System.out.println(sh02.getName());
		System.out.println(sh02.getBirthday());
		//修改Date对象的值
		date.setTime(4342342342L) ;
		System.out.println(sh01.getBirthday()); //改变了
		System.out.println(sh02.getBirthday()); //改变了
	}
	
	/**
	* @Name: deepCopy
	* @Description: 深克隆测试类
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-10 下午7:24:06
	* @Parameters: @throws Exception
	* @Return: void
	 */
	@Test
	public void deepCopy() throws Exception {
		Date date = new Date(12323122312L) ;
		DeepCopySheep sh01 = new DeepCopySheep("单利", date) ;
		System.out.println(sh01.getName());
		System.out.println(sh01.getBirthday());
		DeepCopySheep sh02 = (DeepCopySheep) sh01.clone() ; //浅克隆
		System.out.println(sh02.getName());
		System.out.println(sh02.getBirthday());
		//修改Date对象的值
		date.setTime(4342342342L) ;
		System.out.println(sh01.getBirthday()); //改变了
		System.out.println(sh02.getBirthday()); //没有改变
	}
	
	/**
	* @Name: serializableCopy
	* @Description: 利用序列化、反序列化技术实现对象的深复制
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-10 下午7:37:21
	* @Parameters: 
	* @Return: void
	 */
	@Test
	public void serializableCopy() throws Exception {
		Date date = new Date(1242342342L) ;
		Sheep sh01 = new Sheep("多利", date) ;
		System.out.println(sh01.getName());
		System.out.println(sh01.getBirthday());
		//将sh01对象进行序列化
		ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
		ObjectOutputStream oos = new ObjectOutputStream(baos) ;
		oos.writeObject(sh01) ; //将sh01对象序列化到字节数组输出流中
		byte[] bytes = baos.toByteArray() ;
		//将对象字节数组数据反序列化为新的对象，实现深复制
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes) ;
		ObjectInputStream ois = new ObjectInputStream(bais) ;
		Sheep sh02 = (Sheep) ois.readObject() ;
		System.out.println(sh02.getName());
		System.out.println(sh02.getBirthday());
		//修改日期对象
		date.setTime(432231232131L) ;
		System.out.println(sh01.getBirthday()); //改变了
		System.out.println(sh02.getBirthday()); //没有改变
	}
	

}










